import React, { useState } from 'react';
import { Table, Button, Tag, Space, Modal, Form, Input, Select, Tree, Switch, message, Card } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined, DragOutlined } from '@ant-design/icons';
import './MenuManagement.css';

const { Option } = Select;
const { TreeNode } = Tree;

const MenuManagement = () => {
  const [menus, setMenus] = useState([
    { 
      id: 1, 
      title: '用户管理', 
      key: 'users', 
      icon: 'UserOutlined', 
      path: '/users', 
      parentId: null, 
      order: 1, 
      visible: true, 
      status: '启用',
      children: []
    },
    { 
      id: 2, 
      title: '管理员管理', 
      key: 'admins', 
      icon: 'TeamOutlined', 
      path: '/admins', 
      parentId: null, 
      order: 2, 
      visible: true, 
      status: '启用',
      children: []
    },
    { 
      id: 3, 
      title: '角色权限', 
      key: 'roles', 
      icon: 'SafetyOutlined', 
      path: '/roles', 
      parentId: null, 
      order: 3, 
      visible: true, 
      status: '启用',
      children: []
    },
    { 
      id: 4, 
      title: '操作日志', 
      key: 'logs', 
      icon: 'HistoryOutlined', 
      path: '/logs', 
      parentId: null, 
      order: 4, 
      visible: true, 
      status: '启用',
      children: []
    },
    { 
      id: 5, 
      title: '系统设置', 
      key: 'settings', 
      icon: 'SettingOutlined', 
      path: '/settings', 
      parentId: null, 
      order: 5, 
      visible: false, 
      status: '禁用',
      children: [
        { 
          id: 6, 
          title: '基础设置', 
          key: 'basic-settings', 
          icon: 'SettingOutlined', 
          path: '/settings/basic', 
          parentId: 5, 
          order: 1, 
          visible: true, 
          status: '启用',
          children: []
        },
        { 
          id: 7, 
          title: '安全设置', 
          key: 'security-settings', 
          icon: 'SafetyOutlined', 
          path: '/settings/security', 
          parentId: 5, 
          order: 2, 
          visible: true, 
          status: '启用',
          children: []
        }
      ]
    }
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState(null);
  const [form] = Form.useForm();

  const showModal = (menu = null) => {
    setEditingMenu(menu);
    if (menu) {
      form.setFieldsValue(menu);
    } else {
      form.resetFields();
    }
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingMenu(null);
    form.resetFields();
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      if (editingMenu) {
        // 编辑菜单
        const updateMenu = (menuList) => {
          return menuList.map(item => {
            if (item.id === editingMenu.id) {
              return { ...item, ...values };
            }
            if (item.children && item.children.length > 0) {
              return { ...item, children: updateMenu(item.children) };
            }
            return item;
          });
        };
        setMenus(updateMenu(menus));
        message.success('菜单更新成功');
      } else {
        // 添加新菜单
        const newMenu = {
          id: Math.max(...menus.flatMap(m => [m.id, ...(m.children || []).map(c => c.id)])) + 1,
          ...values,
          children: [],
          status: '启用',
          visible: true
        };
        
        if (values.parentId) {
          // 添加为子菜单
          const addToParent = (menuList) => {
            return menuList.map(item => {
              if (item.id === values.parentId) {
                return { 
                  ...item, 
                  children: [...(item.children || []), newMenu] 
                };
              }
              if (item.children && item.children.length > 0) {
                return { ...item, children: addToParent(item.children) };
              }
              return item;
            });
          };
          setMenus(addToParent(menus));
        } else {
          // 添加为顶级菜单
          setMenus([...menus, newMenu]);
        }
        message.success('新菜单添加成功');
      }
      setIsModalVisible(false);
      setEditingMenu(null);
      form.resetFields();
    });
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个菜单吗？删除后子菜单也会被删除。',
      onOk() {
        const deleteMenu = (menuList) => {
          return menuList.filter(item => item.id !== id).map(item => {
            if (item.children && item.children.length > 0) {
              return { ...item, children: deleteMenu(item.children) };
            }
            return item;
          });
        };
        setMenus(deleteMenu(menus));
        message.success('菜单删除成功');
      },
    });
  };

  const handleToggleVisible = (id, visible) => {
    const toggleVisible = (menuList) => {
      return menuList.map(item => {
        if (item.id === id) {
          return { ...item, visible };
        }
        if (item.children && item.children.length > 0) {
          return { ...item, children: toggleVisible(item.children) };
        }
        return item;
      });
    };
    setMenus(toggleVisible(menus));
    message.success(visible ? '菜单已显示' : '菜单已隐藏');
  };

  const handleToggleStatus = (id, status) => {
    const toggleStatus = (menuList) => {
      return menuList.map(item => {
        if (item.id === id) {
          return { ...item, status };
        }
        if (item.children && item.children.length > 0) {
          return { ...item, children: toggleStatus(item.children) };
        }
        return item;
      });
    };
    setMenus(toggleStatus(menus));
    message.success(status === '启用' ? '菜单已启用' : '菜单已禁用');
  };

  const renderTreeNodes = (data) => {
    return data.map(item => (
      <TreeNode
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
            <span>
              <span style={{ marginRight: 8 }}>{item.title}</span>
              <Tag color={item.visible ? 'green' : 'red'} size="small">
                {item.visible ? '显示' : '隐藏'}
              </Tag>
              <Tag color={item.status === '启用' ? 'blue' : 'orange'} size="small">
                {item.status}
              </Tag>
            </span>
            <Space size="small">
              <Switch
                checked={item.visible}
                onChange={(checked) => handleToggleVisible(item.id, checked)}
                size="small"
                checkedChildren="显"
                unCheckedChildren="隐"
              />
              <Switch
                checked={item.status === '启用'}
                onChange={(checked) => handleToggleStatus(item.id, checked ? '启用' : '禁用')}
                size="small"
                checkedChildren="启"
                unCheckedChildren="禁"
              />
              <Button
                type="link"
                icon={<EditOutlined />}
                size="small"
                onClick={() => showModal(item)}
              >
                编辑
              </Button>
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                size="small"
                onClick={() => handleDelete(item.id)}
              >
                删除
              </Button>
            </Space>
          </div>
        }
        key={item.id}
        dataRef={item}
      >
        {item.children && item.children.length > 0 && renderTreeNodes(item.children)}
      </TreeNode>
    ));
  };

  const getParentOptions = () => {
    const flattenMenus = (menuList, parentId = null, level = 0) => {
      let options = [];
      menuList.forEach(menu => {
        if (menu.id !== editingMenu?.id) {
          options.push({
            value: menu.id,
            label: '  '.repeat(level) + menu.title
          });
          if (menu.children && menu.children.length > 0) {
            options = options.concat(flattenMenus(menu.children, menu.id, level + 1));
          }
        }
      });
      return options;
    };
    return flattenMenus(menus);
  };

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '菜单标识',
      dataIndex: 'key',
      key: 'key',
      width: 150,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 120,
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      width: 150,
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order',
      width: 80,
    },
    {
      title: '显示状态',
      dataIndex: 'visible',
      key: 'visible',
      width: 100,
      render: (visible) => (
        <Tag color={visible ? 'green' : 'red'}>
          {visible ? '显示' : '隐藏'}
        </Tag>
      ),
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === '启用' ? 'blue' : 'orange'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>菜单管理</h2>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={() => showModal()}
        >
          添加菜单
        </Button>
      </div>

      <Card title="菜单树形结构" style={{ marginBottom: 16 }}>
        <Tree
          showLine
          blockNode
          defaultExpandAll
        >
          {renderTreeNodes(menus)}
        </Tree>
      </Card>

      <Card title="菜单列表">
        <Table 
          columns={columns} 
          dataSource={menus.flatMap(menu => [menu, ...(menu.children || [])])} 
          rowKey="id"
          pagination={{
            total: menus.flatMap(menu => [menu, ...(menu.children || [])]).length,
            showTotal: (total) => `共 ${total} 条记录`,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSize: 10
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal
        title={editingMenu ? '编辑菜单' : '添加菜单'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            order: 1,
            visible: true,
            status: '启用'
          }}
        >
          <Form.Item
            name="title"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          
          <Form.Item
            name="key"
            label="菜单标识"
            rules={[{ required: true, message: '请输入菜单标识' }]}
          >
            <Input placeholder="请输入菜单标识（如：users, roles）" />
          </Form.Item>
          
          <Form.Item
            name="icon"
            label="图标"
            rules={[{ required: true, message: '请输入图标名称' }]}
          >
            <Input placeholder="请输入图标名称（如：UserOutlined, SafetyOutlined）" />
          </Form.Item>
          
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径' }]}
          >
            <Input placeholder="请输入路径（如：/users, /roles）" />
          </Form.Item>
          
          <Form.Item
            name="parentId"
            label="父级菜单"
          >
            <Select placeholder="请选择父级菜单（不选则为顶级菜单）" allowClear>
              {getParentOptions().map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="order"
            label="排序"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <Input type="number" placeholder="请输入排序值（数字越小越靠前）" />
          </Form.Item>
          
          <Form.Item
            name="visible"
            label="显示状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="启用状态"
          >
            <Select placeholder="请选择状态">
              <Option value="启用">启用</Option>
              <Option value="禁用">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;